#!/usr/bin/env python
#-*- coding:UTF-8 -*-
#####################################################
# Author: Jiaion - jiaion21@gmail.com
# Last modified:	2011-05-03 21:51
# Filename:	ExecQueue.py
#####################################################

import os
import sys
import time
import daemon
from multiprocessing import Process, Queue
from os.path import abspath, dirname, join

sys.path.insert(0, abspath(join(dirname(__file__), "../")))
sys.path.insert(0, abspath(join(dirname(__file__), "../lib")))

import settings
import Jredis as redis


#Sendmail进程实例
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def Send_mail(mail_user,mail_pass,mail_server,to_list,Mail):
    '''
    to_list: send object
    sub: subject
    msg: content
    send_mail("jiaion@163.com","sub","msg")
    '''
    MIMEText._charset = 'utf-8' 
    i, j, k = mail_server.split(".")
    mail_postfix = j+"."+k
    from_mail = mail_user + "<" + mail_user + "@" + mail_postfix + ">"
    mail_user = mail_user + "@" + mail_postfix
    data = MIMEMultipart('alternative')
    HtmlMsg = MIMEText(Mail,'html',_charset='utf-8')
    TextMsg = MIMEText('Text','plain',_charset='utf-8')
    data.attach(HtmlMsg)
    sub = 'OPMS系统密码'
    data['Subject'] = sub
    data['From'] = from_mail
    data['To'] = ";".join(to_list)
    print data
    try:
        s = smtplib.SMTP()
        s.connect(mail_server)
        s.login(mail_user, mail_pass)
        s.sendmail(from_mail, to_list, data.as_string())
        s.quit()
        return True
    except Exception, e:
        print str(e)
        return False

def Getmail():
    while True:
        Work = redis.lpops("USERREG")
        if Work:
            try :
                if Work.get('Type') == 'SendUser':
                    msg = Work.get('Mail').encode('utf-8') + Work.get('Pass').encode('utf-8')
                    mailadd_list = [ Work.get('User') + u'@rekoo.com' ]
                else :
                    msg = Work.get('Mail').encode('utf-8')
                    mailadd_list = Work.get('ToList')
            except AttributeError:
                pass
            mail_server = 'mail.163.com'
            mail_user = 'user'
            mail_pass = 'password'
            Send_mail(mail_user,mail_pass,mail_server,mailadd_list,msg)
        time.sleep(60)


#Command进程实例
def WorkInstance(Queue):
    while True:
        KEY = Queue.get()
        if KEY:
            HOSTS = KEY.get('HOSTS')
            COMMAND = KEY.get('COMMAND')
            SID = KEY.get('SID')
            if HOSTS and COMMAND and SID:
                try :
                    import Fabric
                    FILE = '%s%s.log' % (settings.LOGDIR,SID)
                    Fabric.FILE = FILE
                    STDFI = open(FILE,'w')
                    sys.stdout = STDFI
                    sys.stderr = STDFI
                    for i in HOSTS:
                        Fabric.env.host_string = i
                        Exec = Fabric
                        exec("Exec.%s()" % COMMAND)
                    del Exec
                    del sys.modules['Fabric']
                except :
                    print sys.exc_info()
                    pass
                STDFI.close()
        time.sleep(5)


def Main():
    daemon.daemonize(noClose=True)
    WorkNum = 4
    WorkQueue = Queue()

    WorkList = []

    #启动工作进程
    for i in xrange(WorkNum):
        P = Process(target=WorkInstance, args=(WorkQueue,))
        WorkList.append(P)

    for x in WorkList:
        x.start()


    #启动Sendmail工作进程
    MailWork = Process(target=Getmail, args=())
    MailWork.start()



    #从redis中获得队列内容
    while True:
        try:
            RedQueue = redis.lpops('CommQueue')
        except TypeError:
            time.sleep(2)
        else:
            WorkQueue.put(RedQueue)
        time.sleep(2)

if __name__ == "__main__":
    Main()
